#include "CH58x_common.h"
#include "stdint.h"
#include "stdio.h"
#include "DevicesSPI.h"


void vSPI0Init(void)
{
    GPIOA_SetBits(GPIO_Pin_12);

    GPIOA_ModeCfg(GPIO_Pin_12 | GPIO_Pin_13 | GPIO_Pin_14, GPIO_ModeOut_PP_5mA);
    GPIOA_ModeCfg(GPIO_Pin_15, GPIO_ModeIN_PU);

    R8_SPI0_CLOCK_DIV = 4;
    R8_SPI0_CTRL_MOD = RB_SPI_ALL_CLEAR;
    R8_SPI0_CTRL_MOD = RB_SPI_MOSI_OE | RB_SPI_SCK_OE;

    /* 访问BUFFER/FIFO自动清除IF_BYTE_END标志 */
    R8_SPI0_CTRL_CFG |= RB_SPI_AUTO_IF;
    /* 不启动DMA方式 */
    R8_SPI0_CTRL_CFG &= ~RB_SPI_DMA_ENABLE;
}

void vSPIWriteByte(uint32_t uiSpi, uint8_t ucByte)
{
    uint32_t uiTime;

    R8_SPI0_CTRL_MOD &= ~RB_SPI_FIFO_DIR;
    R16_SPI0_TOTAL_CNT = 1;
    R8_SPI0_FIFO = ucByte;

    while((R8_SPI0_INT_FLAG & RB_SPI_FREE) == 0);
}

uint8_t ucSPIReadByte(uint32_t uiSpi)
{
    R8_SPI0_CTRL_MOD |= RB_SPI_FIFO_DIR;
    R8_SPI0_BUFFER = 0xFF;
    while((R8_SPI0_INT_FLAG & RB_SPI_FREE) == 0);

    return R8_SPI0_BUFFER;
}

int8_t cSPIWriteDatas(uint32_t uiSpi, void *pvDatas, int32_t iLength)
{
    uint8_t *pucDatas = pvDatas;

    R8_SPI0_CTRL_MOD   &= ~RB_SPI_FIFO_DIR;
    R8_SPI0_INT_FLAG    = RB_SPI_IF_CNT_END;
    R16_SPI0_TOTAL_CNT  = iLength;

    while(iLength > 0)
    {
        if(R8_SPI0_FIFO_COUNT < SPI_FIFO_SIZE)
        {
            R8_SPI0_FIFO = *pucDatas++;
            iLength--;
        }
    }

    while(R8_SPI0_FIFO_COUNT != 0);
}

int8_t cSPIReadDatas(uint32_t uiSpi, void *pvDatas, int32_t iLength)
{
    uint8_t *pucDatas = pvDatas;

    R8_SPI0_CTRL_MOD   |= RB_SPI_FIFO_DIR;
    R8_SPI0_INT_FLAG    = RB_SPI_IF_CNT_END;
    /* 设置需要接收的数据长度，FIFO方向为输入、长度不为0则会启动传输 */
    R16_SPI0_TOTAL_CNT  = iLength;

    while(iLength > 0)
    {
        if(R8_SPI0_FIFO_COUNT)
        {
            *pucDatas++ = R8_SPI0_FIFO;
            iLength--;
        }
    }
}
